$(function () {
    let buttonGroup = [
        {
            id: 'btn_add',
            size: 'small',
            text: '新增收款',
            iconCls: 'icon-add',
            plain: true,
            onClick: btn_add
        },
        {
            id: 'btn_modify',
            size: 'small',
            text: '修改收款',
            iconCls: 'icon-edit',
            plain: true,
            onClick: btn_modify
        },
        {
            id: 'btn_modify_price',
            size: 'small',
            text: '修改单价',
            iconCls: 'icon-edit',
            plain: true,
            onClick: btn_modify_price
        },
        {
            id: 'btn_cancel_filter',
            size: 'small',
            text: '清除过滤',
            iconCls: 'icon-clear',
            plain: true,
            onClick: btn_cancel_filter
        },
        {
            id: 'btn_export',
            size: 'small',
            text: '导出Excel',
            iconCls: 'icon-page_excel',
            plain: true,
            onClick: btn_export_excel
        },
        {
            id: 'btn_print',
            size: 'small',
            text: '打印',
            iconCls: 'icon-print',
            plain: true,
            onClick: btn_print
        },
        {
            id: 'btn_grid_columns',
            size: 'small',
            text: '列',
            iconCls: 'icon-text_columns',
            plain: true,
            onClick: btn_open_column_list
        },
        {
            id: 'btn_close', size: 'small', text: '关闭', iconCls: 'icon-no', onClick: btn_close,
            plain: true
        },
    ];
    buttonGen($('#north'), buttonGroup);
    bindEnterEvents();
    let kGrid = $('#v_grid').data('kendoGrid');
    var options = kGrid.getOptions();
    if (options.columns.length > 0)
        initCombobox(options)
})

function setBtnState(b) {
    if (b) {
        $('#btn_add').linkbutton('enable');
        $('#btn_modify').linkbutton('enable');
        $('#btn_modify_price').linkbutton('enable');
    } else {
        $('#btn_add').linkbutton('disable');
        $('#btn_modify').linkbutton('disable');
        $('#btn_modify_price').linkbutton('disable');
    }
}

//  选中事件
function onSelect(title, index) {
    function state(f) {
        if (!f && index == 0) {
            $('#contactCompanyId').combobox('clear');
            $('#contactCompanyId').combobox('disable');
            $('#start').datebox('disable');
            $('#end').datebox('disable');
        } else {
            $('#start').datebox('enable');
            $('#end').datebox('enable');
            $('#contactCompanyId').combobox('enable');
        }
    }

    switch (index) {
        case 0:// 应收账款
            if ($('#v_grid_3').data('kendoGrid') == undefined) {
                grid_4();
            }
            break;
        case 1:// 已收账款
            if ($('#v_grid_4').data('kendoGrid') == undefined) {
                grid_5();
            }
            break;
    }
    setBtnState(index == 0);
    if (index >= 0) {
        $('#state').switchbutton('enable');
    } else {
        $('#state').switchbutton('disable');
    }
    state($('#state').switchbutton('options').checked)
}

/**
 * 2021年8月10日 14:58:07 chanchaw
 * 应收应付 - 应收管理 - 应收账款
 */
function grid_4() {
    let SUFFIX = "_d";
    let client = new kendo.data.DataSource({data: []});
    let address = new kendo.data.DataSource({data: []});
    let collectiontype = new kendo.data.DataSource({data: []});
    let specification = new kendo.data.DataSource({data: []});
    let dataSource = new kendo.data.DataSource({
        transport: {
            read: {// 后端控制器 ...\controller\DeliveryReportController.java
                url: "delivery/report/receivedtl",
                dataType: "json",
                type: "GET",
                data: {
                    start: $('#start').datebox('getValue'),
                    end: $('#end').datebox('getValue'),
                    clientName: $('#contactCompanyId').combobox('getValue') || '',
                    value: $('#state').switchbutton('options').checked ? 0 : 1
                    // textField: $('#column').combobox('getValue'),
                    // valueField: $('#value').textbox('getValue'),
                }
            }
        },
        schema: {
            model: {
                id: 'id',
                fields: {
                    billdate: {type: "date"},
                    ps: {type: "number"},
                    qty: {type: "number"},
                    price: {type: "number"},
                    account_price: {type: "number"},
                    money: {type: "number"},
                    accoumlatedtoday: {type: "number"},
                    qty_jz: {type: "number"},
                    meter_number: {type: "number"},
                    ticket_money: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "ps", aggregate: "sum"},
            {field: "qty", aggregate: "sum"},
            {field: "money", aggregate: "sum"},
            {field: "qty_jz", aggregate: "sum"},
            {field: "meter_number", aggregate: "sum"},
            {field: "ticket_money", aggregate: "sum"},
        ],
        change: function (e) {
            let data = this.data();
            client.data(unique(data, 'client'));
            address.data(unique(data, 'address'));
            specification.data(unique(data, 'pmgg'));
            collectiontype.data(unique(data, 'collectiontype'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })
        }
    });
    let columns = [
        {field: "no", title: "#", filterable: false, template: "<span class='row_number'></span>", width: 40},
        {
            field: "id",
            title: '编号',
            width: 93,
            hidden: true,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
        },
        {
            field: "whitebillfhid",
            title: '编号2',
            width: 93,
            hidden: true,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
        },
        {
            field: "cp_billfh_id",
            title: '编号3',
            width: 93,
            hidden: true,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
        },
        {
            field: "dye_fabric_inbound_id",
            title: '编号4',
            width: 93,
            hidden: true,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
        },
        {
            field: "planid",
            title: '编号5',
            width: 93,
            hidden: true,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
        },
        {
            field: "billdate",
            title: '日期',
            width: 93,
            format: "{0: yyyy-MM-dd}",
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: false
        },
        {
            field: "client",
            title: '客户',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: false
        },
        {
            field: "billcode",
            title: '单据编号',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: false
        },
        {
            field: "type",
            title: '单据类型',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: false
        },
        {
            field: "billtype",
            title: '项目',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: false
        },
        {
            field: "collectiontype",
            title: '类型',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: false
        },
        {
            field: "price_standard",
            title: '计价标准',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: false
        },
        {
            field: "ps",
            title: '匹数',
            hidden: true,
            width: 93,
            template: item => item['ps'] ? parseFloat(item['ps']).toFixed(0) : '',
            footerTemplate: '#=kendo.format("{0:n0}",sum || 0)#',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "qty",
            title: '毛重',
            width: 93,
            template: item => item['qty'] ? parseFloat(item['qty']).toFixed(1) : '',
            footerTemplate: '#=kendo.format("{0:n1}",sum||0)#',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "qty_jz",
            title: '净重',
            width: 93,
            template: item => item['qty_jz'] ? parseFloat(item['qty_jz']).toFixed(1) : '',
            footerTemplate: '#=kendo.format("{0:n1}",sum||0)#',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "meter_number",
            title: '米数',
            width: 93,
            template: item => item['meter_number'] ? parseFloat(item['meter_number']).toFixed(1) : '',
            footerTemplate: '#=kendo.format("{0:n1}",sum||0)#',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },

        /*{
            field: "price",
            title: '单价',
            width: 93,
            hidden: true,
            template: item => item['price'] ? parseFloat(item['price']).toFixed(2) : '',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },*/
        {
            field: "account_price",
            title: '对账单价',
            width: 93,
            template: item => item['account_price'] ? parseFloat(item['account_price']).toFixed(2) : '',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "money",
            title: '金额',
            width: 93,
            template: item => item['money'] ? parseFloat(item['money']).toFixed(2) : '',
            footerAttributes: {'style': 'text-align:right;'},
            footerTemplate: '#=kendo.format("{0:n2}",sum||0)#',
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "ticket_money",
            title: '开票金额',
            width: 93,
            template: item => item['ticket_money'] ? parseFloat(item['ticket_money']).toFixed(2) : '',
            footerAttributes: {'style': 'text-align:right;'},
            footerTemplate: '#=kendo.format("{0:n2}",sum||0)#',
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "accoumlatedtoday",
            title: '本日累计',
            width: 93,
            template: item => item['accoumlatedtoday'] ? parseFloat(item['accoumlatedtoday']).toFixed(2) : '',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "billmemo",
            title: '备注',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: false
        },
        {
            field: "SKid",
            title: '收款编号',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            hidden: true,
            filterable: false
        },
    ];
    let grid = $("#v_grid_3").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "应收款.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });
        },
        columnHide: function (e) {
            //列隐藏事件
            if (!$('#state').switchbutton('options').checked) return;
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
        },
        columnShow: function (e) {
            if (!$('#state').switchbutton('options').checked) return;
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null, SUFFIX);
        },
        columnResize: function (e) {
            if (!$('#state').switchbutton('options').checked) return;
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null, SUFFIX);
            }
        },
        columnReorder: function (e) {
            if (!$('#state').switchbutton('options').checked) return;
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field'] + SUFFIX
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_grid_3').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    grid01.setOptions({
        columns: columns
    });
    grid.on('dblclick', 'tr', function (e) {
        //  双击打开原单
        let kGrid = $("#v_grid_3").data("kendoGrid");
        let dataItem = kGrid.dataItem(e.currentTarget);
        if (dataItem != undefined && dataItem['SKid']) {
            btn_modify();
        } else if (!$('#state').switchbutton('options').checked) {
            let client = dataItem['client'];
            $('#contactCompanyId').combobox('setValue', client);
            $('#state').switchbutton('check');
        }
    });
}

/**
 * 2021年8月10日 14:58:07 chanchaw
 * 应收应付 - 应收管理 - 已收账款
 */
function grid_5() {
    let SUFFIX = "_e";
    let client = new kendo.data.DataSource({data: []});
    let dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "delivery/report/received",
                dataType: "json",
                type: "GET",
                data: {
                    start: $('#start').datebox('getValue'),
                    end: $('#end').datebox('getValue'),
                    clientName: $('#contactCompanyId').combobox('getValue'),
                    value: $('#state').switchbutton('options').checked ? 0 : 1
                    // textField: $('#column').combobox('getValue'),
                    // valueField: $('#value').textbox('getValue'),
                }
            }
        },
        schema: {
            model: {
                id: 'id',
                fields: {
                    money: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "money", aggregate: "sum"},
        ],
        change: function (e) {
            let data = this.data();
            client.data(unique(data, 'client'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })

        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })
        }
    });
    let columns = [
        {field: "no", title: "#", filterable: false, template: "<span class='row_number'></span>", width: 40},
        {
            field: "id",
            title: '编号',
            width: 93,
            hidden: true,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
        },
        {
            field: "client",
            title: '客户',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: false
        },
        {
            field: "billtype",
            title: '项目',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: false
        },
        {
            field: "collectiontype",
            title: '收款类型',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: false
        },
        {
            field: "money",
            title: '金额',
            width: 93,
            template: item => item['money'] ? parseFloat(item['money']).toFixed(2) : '',
            footerAttributes: {'style': 'text-align:right;'},
            footerTemplate: '#=kendo.format("{0:n2}",sum)#',
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "billdate",
            title: '日期',
            width: 85,
            headerAttributes: {'style': 'text-align:center;'},
            format: "{0: yyyy-MM-dd}",
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;text-align:center;'},
            filterable: false
        },
        {
            field: "billmemo",
            title: '备注',
            width: 93,
            attributes: {'style': 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: false
        },
    ];
    let grid = $("#v_grid_4").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "已收款序时表.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });
        },
        columnHide: function (e) {
            if (!$('#state').switchbutton('options').checked) return;
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
        },
        columnShow: function (e) {
            if (!$('#state').switchbutton('options').checked) return;
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null, SUFFIX);
        },
        columnResize: function (e) {
            if (!$('#state').switchbutton('options').checked) return;
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null, SUFFIX);
            }
        },
        columnReorder: function (e) {
            if (!$('#state').switchbutton('options').checked) return;
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field'] + SUFFIX
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_grid_4').data('kendoGrid');
    grid.on('dblclick', 'tr', function (e) {
        //  双击打开原单
        let kGrid = $("#v_grid_4").data("kendoGrid");
        let dataItem = kGrid.dataItem(e.currentTarget);
        if (!$('#state').switchbutton('options').checked) {
            let client = dataItem['client'];
            $('#contactCompanyId').combobox('setValue', client);
            $('#state').switchbutton('check');
        }
    });
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    grid01.setOptions({
        columns: columns
    });
}

function btn_cancel_filter() {
    switch (getCurrentIndex()) {
        case 0:
            $('#v_grid_3').data('kendoGrid').dataSource.filter({});
            break;
        case 1:
            $('#v_grid_4').data('kendoGrid').dataSource.filter({});
            break;
    }
}

function btn_search() {
    function setCol(ele, show = []) {
        let kGrid = ele.data('kendoGrid');
        let columns = kGrid.columns;
        let checked = $('#state').switchbutton('options').checked;
        if (!checked)
            for (let col of columns) {
                if (col['field'] && show.indexOf(col['field']) == -1) {
                    kGrid.hideColumn(col);
                } else if (col['field']) {
                    kGrid.showColumn(col);
                }
            }
        else {
            for (let col of columns) {
                if (col['title'] && col['title'].indexOf('编号') > -1)
                    kGrid.hideColumn(col);
                else
                    kGrid.showColumn(col);
            }
        }
    }

    switch (getCurrentIndex()) {
        case 0:
            $('#v_grid_3').data('kendoGrid').dataSource.read({
                start: $('#start').datebox('getValue'),
                end: $('#end').datebox('getValue'),
                clientName: $('#contactCompanyId').combobox('getValue'),
                checkType: $('#type').combobox('getValue'),
                value: $('#state').switchbutton('options').checked ? 0 : 1
                // textField: $('#column').combobox('getValue'),
                // valueField: $('#value').textbox('getValue'),
            });
            setCol($('#v_grid_3'), ['no', 'client', 'money']);
            break;
        case 1:
            $('#v_grid_4').data('kendoGrid').dataSource.read({
                start: $('#start').datebox('getValue'),
                end: $('#end').datebox('getValue'),
                clientName: $('#contactCompanyId').combobox('getValue'),
                value: $('#state').switchbutton('options').checked ? 0 : 1
                // textField: $('#column').combobox('getValue'),
                // valueField: $('#value').textbox('getValue'),
            });
            setCol($('#v_grid_4'), ['no', 'client', 'money']);
            break;
    }
}

function btn_add() {
    let columns = [
        {
            field: 'client',
            title: '客户',
            editor: {
                type: 'combobox', options: {
                    url: 'contactCompany/listQuery',
                    method: 'GET', queryParams: {state: 1},
                    textField: 'companyName', valueField: 'companyName',
                    panelHeight: 200,
                    required: true,
                    onLoadSuccess: function () {
                        $(this).combobox('options').limitToList = true;
                        if (!$(this).combobox('getValue')) {
                            let loadData = $(this).combobox('getData') || [];
                            let opts = $(this).combobox('options');
                            if (loadData.length > 0) {
                                $(this).combobox('setValue', loadData[0][opts.valueField]);
                            }
                        }
                    }
                }
            }
        },
        {
            field: 'billdate',
            title: '日期',
            editor: {type: 'datebox', options: {required: true, value: getCurrentDate()}}
        },
        {
            field: 'billtype',
            title: '项目',
            editor: {
                type: 'combobox', options: {
                    required: true,
                    data: [{value: '收款'}, {value: '收款调整'}, {value: '开票'}],
                    textField: 'value',
                    valueField: 'value',
                    limitToList: true,
                    panelHeight: 'auto',
                    onChange: function (newVal, oldVal) {
                        if (newVal == '收款调整' || newVal == '开票') {
                            $('#collectiontypeInput').combobox('clear');
                            $('#collectiontypeInput').combobox('disable');
                        } else {
                            $('#collectiontypeInput').combobox('enable');
                        }
                    }
                }
            }
        },
        {
            field: 'money',
            title: '金额',
            editor: {type: 'numberbox', options: {precision: 2, required: true,}}
        },
        {
            field: 'collectiontype',
            id: 'collectiontypeInput',
            title: '收款类型',
            editor: {
                type: 'combobox', options: {
                    data: [{value: '转账'}, {value: '承兑'}, {value: '现金'}],
                    textField: 'value',
                    valueField: 'value',
                    limitToList: true,
                    panelHeight: 'auto'
                }
            }
        },
        {
            field: 'billmemo',
            title: '备注',
            editor: {type: 'textbox', options: {multiline: true, height: 100}}
        }
    ];
    let loadData = {};
    let clientName = $('#contactCompanyId').combobox('getValue');
    if (clientName) {
        loadData.client = clientName;
    }
    openDialog({
        loadData: loadData,
        columns: columns,
        height: 380,
        width: 330,
        mode: '新增收款',
        buttons: [{
            text: '保存', iconCls: 'icon-save', handler: e => {
                let dialog = $('.form-dialog-edit');
                if (!$(dialog.find('form')).form('validate')) {
                    return;
                }
                let param = $(dialog.find('form')).serializeObject();
                let url = 'receivables/insertSelective';
                //  修改
                $.messager.progress({
                    title: '',
                    msg: '请稍等...',
                    interval: 5000
                });
                $.ajax({
                    url: url,
                    type: 'POST',
                    dataType: 'json',
                    data: param,
                    success: function (data) {
                        if (data.success) {
                            btn_search();
                            $.formDialog.close();
                            $.messager.show({title: '提示', msg: data.message});
                        } else {
                            $.messager.alert('提示', data.message, 'warning');
                        }
                    },
                    complete: function () {
                        $.messager.progress('close');
                    }
                })
            }
        }, {
            text: '取消', iconCls: 'icon-cancel', handler: e => {
                $.formDialog.close();
            }
        }]
    });
}

function btn_modify() {
    let kGrid = $('#v_grid_3').data('kendoGrid');
    let dataItem = kGrid.dataItem(kGrid.select());
    if (dataItem == undefined || !dataItem['SKid']) {
        $.messager.alert('提示', '请选中收款或收款调整', 'warning');
        return;
    }
    let columns = [
        {
            field: 'id',
            title: '编号',
        },
        {
            field: 'client',
            title: '客户',
            editor: {
                type: 'combobox', options: {
                    url: 'contactCompany/listQuery',
                    method: 'GET', queryParams: {state: 1},
                    textField: 'companyName', valueField: 'companyName',
                    panelHeight: 200,
                    required: true,
                    onLoadSuccess: function () {
                        $(this).combobox('options').limitToList = true;
                    }
                }
            }
        },
        {
            field: 'billdate',
            title: '日期',
            editor: {type: 'datebox', options: {required: true, value: getCurrentDate()}}
        },
        {
            field: 'billtype',
            title: '项目',
            editor: {
                type: 'combobox', options: {
                    required: true,
                    data: [{value: '收款'}, {value: '收款调整'}, {value: '开票'}],
                    textField: 'value',
                    valueField: 'value',
                    panelHeight: 'auto',
                    limitToList: true,
                    onChange: function (newVal, oldVal) {
                        if (newVal == '收款调整' || newVal == '开票') {
                            $('#collectiontypeInput').combobox('clear');
                            $('#collectiontypeInput').combobox('disable');
                        } else {
                            $('#collectiontypeInput').combobox('enable');
                        }
                    }
                }
            }
        },
        {
            field: 'money',
            title: '金额',
            editor: {type: 'numberbox', options: {precision: 2, required: true,}}
        },
        {
            field: 'collectiontype',
            id: 'collectiontypeInput',
            title: '收款类型',
            editor: {
                type: 'combobox', options: {
                    data: [{value: '转账'}, {value: '承兑'}, {value: '现金'}],
                    textField: 'value',
                    valueField: 'value',
                    limitToList: true,
                    panelHeight: 'auto'
                }
            }
        },
        {
            field: 'billmemo',
            title: '备注',
            editor: {type: 'textbox', options: {multiline: true, height: 100}}
        }
    ];
    openDialog({
        loadData: {
            id: dataItem['SKid'],
            billtype: dataItem.billtype,
            client: dataItem.client,
            money: dataItem.billtype == '开票' ? dataItem['ticket_money'] : -dataItem.money,
            billdate: kendo.toString(dataItem.billdate, 'yyyy-MM-dd'),
            collectiontype: dataItem.collectiontype,
            billmemo: dataItem.billmemo
        },
        columns: columns,
        height: 380,
        width: 330,
        mode: '修改收款',
        buttons: [
            {
                text: '删除收款', iconCls: 'icon-remove', handler: e => {
                    $.messager.confirm('提示', '是否确定删除？删除后不可恢复!', function (r) {
                        if (r) {
                            $.messager.progress({
                                title: '',
                                msg: '请稍等...',
                                interval: 5000
                            });
                            let dialog = $('.form-dialog-edit');
                            let url = 'receivables/deleteByPk';
                            let param = $(dialog.find('form')).serializeObject();
                            $.ajax({
                                url: url,
                                type: 'POST',
                                dataType: 'json',
                                data: {id: param['id'] || 0},
                                success: function (data) {
                                    if (data.success) {
                                        btn_search();
                                        $.formDialog.close();
                                        $.messager.show({title: '提示', msg: data.message});
                                    } else {
                                        $.messager.alert('提示', data.message, 'warning');
                                    }
                                },
                                complete: function () {
                                    $.messager.progress('close');
                                }
                            })
                        }
                    })
                }
            }, {
                text: '保存', iconCls: 'icon-save', handler: e => {
                    let dialog = $('.form-dialog-edit');
                    if (!$(dialog.find('form')).form('validate')) {
                        return;
                    }
                    let param = $(dialog.find('form')).serializeObject();
                    let url = 'receivables/updateSelective';
                    //  修改
                    $.messager.progress({
                        title: '',
                        msg: '请稍等...',
                        interval: 5000
                    });
                    $.ajax({
                        url: url,
                        type: 'POST',
                        dataType: 'json',
                        data: param,
                        success: function (data) {
                            if (data.success) {
                                btn_search();
                                $.formDialog.close();
                                $.messager.show({title: '提示', msg: data.message});
                            } else {
                                $.messager.alert('提示', data.message, 'warning');
                            }
                        },
                        complete: function () {
                            $.messager.progress('close');
                        }
                    })
                }
            }, {
                text: '取消', iconCls: 'icon-cancel', handler: e => {
                    $.formDialog.close();
                }
            }],
        onOpen: function () {
            setTimeout(function () {
                $('.form-dialog-edit').dialog('panel').find('.l-btn').eq(0).css({float: 'left'});
            }, 0)
        }
    });
}

function btn_modify_price() {
    if (getCurrentIndex() != 0) return;
    let permissions = JSON.parse(localStorage.getItem('XZY_USER_PERMISSIONS')) || [];
    if (permissions.indexOf($('body').data('menu_id') + ':PRICE') <= -1) {
        messagerAlert('无权操作！')
    }
    let kGrid = getSelectedGrid();
    let selected = kGrid.dataItem(kGrid.select());
    if (selected['type'] != '白坯发货' && selected['type'] != '色布发货') {
        messagerAlert('只能更改白坯或者色布发货数据！！');
        return;
    }
    if (!$('#state').switchbutton('options').checked) {
        messagerAlert('请选中需要修改的数据！');
        return;
    }
    if (selected == undefined) {
        messagerAlert('请选中需要修改的数据！');
        return;
    }
    switch (selected['type']) {
        case '白坯发货':
            $.ajax({
                url: 'sysConfigInt/selectAllowModifyPriceConfig',
                data: {},
                type: 'GET',
                dataType: 'json',
            }).then(function (data) {
                let disabled = !!!data['configValue'];
                let div = $(`<div class="easyui-dialog">
                 <form style="width: 100%;height: 100%;">
                    <input type="hidden" name="id">
                    <input type="hidden" name="planid">
                    <div class="form-row" style="padding-top: 10px;">
                        <input name="price" class="easyui-numberbox" data-options="required:true,precision:2,min:0,label:'单价：'">
                    </div>
                    <div class="form-row">
                        <label>修改范围：</label>
                        <input name="modifyPart" class="easyui-radiobutton" value="0" data-options="label:'本行',labelPosition:'after',checked:true">
                        <input name="modifyPart" class="easyui-radiobutton" value="1" data-options="disabled:${disabled},label:'本订单',labelPosition:'after'">
                    </div>
                 </form>
                </div>`);
                $.parser.parse(div);
                div.dialog({
                    title: '修改单价',
                    iconCls: 'icon-edit',
                    width: 400,
                    height: 168,
                    resizable: false,
                    modal: true,
                    onClose: function () {
                        $(this).dialog('destroy');
                    },
                    onOpen: function () {
                        $(this).find('form').form('load', {
                            id: selected['whitebillfhid'],
                            planid: selected['planid'],
                            price: selected['account_price']
                        })
                    },
                    buttons: [
                        {
                            text: '保存', iconCls: 'icon-save', handler: e => {
                                let form = div.find('form');
                                if (!form.form('validate')) {
                                    return;
                                }
                                let formData = form.serializeObject();
                                if (formData['modifyPart'] == '1') {
                                    //  本订单
                                    messagerConfirm('本订单的所有发货单价都将改成当前单价，是否继续？', r => {
                                        if (r) {
                                            $.post('plan/modify/price', {
                                                planid: formData.planid,
                                                accountPrice: formData.price
                                            }, function (data) {
                                                if (data.success) {
                                                    div.dialog('close');
                                                    $('#v_grid_3').data('kendoGrid').dataSource.read({
                                                        start: $('#start').datebox('getValue'),
                                                        end: $('#end').datebox('getValue'),
                                                        clientName: $('#contactCompanyId').combobox('getValue'),
                                                        checkType: $('#type').combobox('getValue'),
                                                        value: $('#state').switchbutton('options').checked ? 0 : 1
                                                        // textField: $('#column').combobox('getValue'),
                                                        // valueField: $('#value').textbox('getValue'),
                                                    });
                                                } else {
                                                    messagerAlert(data.message);
                                                }
                                            }, 'json');
                                        }
                                    })
                                } else {
                                    //  本行
                                    $.post('whitebillfh/updateSelective', {
                                        id: formData.id,
                                        accountPrice: formData.price
                                    }, function (data) {
                                        if (data.success) {
                                            div.dialog('close');
                                            $('#v_grid_3').data('kendoGrid').dataSource.read({
                                                start: $('#start').datebox('getValue'),
                                                end: $('#end').datebox('getValue'),
                                                clientName: $('#contactCompanyId').combobox('getValue'),
                                                checkType: $('#type').combobox('getValue'),
                                                value: $('#state').switchbutton('options').checked ? 0 : 1
                                                // textField: $('#column').combobox('getValue'),
                                                // valueField: $('#value').textbox('getValue'),
                                            });
                                        } else {
                                            messagerAlert(data.message);
                                        }
                                    }, 'json');
                                }
                            }
                        },
                        {
                            text: '取消', iconCls: 'icon-cancel', handler: e => {
                                div.dialog('close');
                            }
                        }
                    ]
                });
            })
            break;
        case '色布发货':
            $.ajax({
                url: 'sysConfigInt/selectAllowModifyPriceConfig',
                data: {},
                type: 'GET',
                dataType: 'json',
            }).then(function (data) {
                let disabled = !!!data['configValue'];
                let div = $(`<div class="easyui-dialog">
                 <form style="width: 100%;height: 100%;">
                    <input type="hidden" name="dye_fabric_inbound_id">
                    <input type="hidden" name="cp_billfh_id">
                    <input type="hidden" name="planid">
                    <div class="form-row" style="padding-top: 10px;">
                        <input name="price" class="easyui-numberbox" data-options="required:true,precision:2,min:0,label:'单价：'">
                    </div>
                    <div class="form-row">
                        <label>修改范围：</label>
                        <input name="modifyPart" class="easyui-radiobutton" value="0" data-options="label:'本行',labelPosition:'after',checked:true">
                        <input name="modifyPart" class="easyui-radiobutton" value="1" data-options="disabled:${disabled},label:'本订单',labelPosition:'after'">
                    </div>
                 </form>
                </div>`);
                $.parser.parse(div);
                div.dialog({
                    title: '修改单价',
                    iconCls: 'icon-edit',
                    width: 400,
                    height: 168,
                    resizable: false,
                    modal: true,
                    onClose: function () {
                        $(this).dialog('destroy');
                    },
                    onOpen: function () {
                        $(this).find('form').form('load', {
                            cp_billfh_id: selected['cp_billfh_id'],
                            dye_fabric_inbound_id: selected['dye_fabric_inbound_id'],
                            planid: selected['planid'],
                            price: selected['account_price']
                        })
                    },
                    buttons: [
                        {
                            text: '保存', iconCls: 'icon-save', handler: e => {
                                let form = div.find('form');
                                if (!form.form('validate')) {
                                    return;
                                }
                                let formData = form.serializeObject();
                                if (formData['modifyPart'] == '1') {
                                    //  本订单
                                    messagerConfirm('本订单的所有发货单价都将改成当前单价，是否继续？', r => {
                                        if (r) {
                                            $.post('dyeFabricPlan/modify/price', {
                                                planid: formData.planid,
                                                accountPrice: formData.price
                                            }, function (data) {
                                                if (data.success) {
                                                    div.dialog('close');
                                                    $('#v_grid_3').data('kendoGrid').dataSource.read({
                                                        start: $('#start').datebox('getValue'),
                                                        end: $('#end').datebox('getValue'),
                                                        clientName: $('#contactCompanyId').combobox('getValue'),
                                                        checkType: $('#type').combobox('getValue'),
                                                        value: $('#state').switchbutton('options').checked ? 0 : 1
                                                        // textField: $('#column').combobox('getValue'),
                                                        // valueField: $('#value').textbox('getValue'),
                                                    });
                                                } else {
                                                    messagerAlert(data.message);
                                                }
                                            }, 'json');
                                        }
                                    })
                                } else {
                                    //  本行
                                    const url = formData['dye_fabric_inbound_id'] ? 'dyeFabricInbound/updateSelective' : 'cpBillfh/updateSelective';
                                    $.post(url, {
                                        id: formData['dye_fabric_inbound_id'] ? formData['dye_fabric_inbound_id'] : formData['cp_billfh_id'],
                                        accountPrice: formData.price
                                    }, function (data) {
                                        if (data.success) {
                                            div.dialog('close');
                                            $('#v_grid_3').data('kendoGrid').dataSource.read({
                                                start: $('#start').datebox('getValue'),
                                                end: $('#end').datebox('getValue'),
                                                clientName: $('#contactCompanyId').combobox('getValue'),
                                                checkType: $('#type').combobox('getValue'),
                                                value: $('#state').switchbutton('options').checked ? 0 : 1
                                                // textField: $('#column').combobox('getValue'),
                                                // valueField: $('#value').textbox('getValue'),
                                            });
                                        } else {
                                            messagerAlert(data.message);
                                        }
                                    }, 'json');
                                }
                            }
                        },
                        {
                            text: '取消', iconCls: 'icon-cancel', handler: e => {
                                div.dialog('close');
                            }
                        }
                    ]
                });
            })
            break;
    }

}

function openDialog(opts) {
    $.formDialog.open(opts);
}

function getCurrentIndex() {
    let tab = $('#tabs').tabs('getSelected');
    let index = $('#tabs').tabs('getTabIndex', tab);
    return index;
}

function btn_print() {
    let reportlets = [];
    $.get('customize/getDatabase', {}, data => {
        if (data.success) {
            switch (getCurrentIndex()) {
                case 0:
                    if (!$('#contactCompanyId').combobox('getValue')) {
                        $.messager.alert('提示', '请选择客户再打印！', 'warning');
                        return;
                    }
                    reportlets.push({
                        reportlet: `${data.data}/应收款序时表打印.cpt`,
                        Sdate: $('#start').datebox('getValue'),
                        Edate: $('#end').datebox('getValue'),
                        clientName: $('#contactCompanyId').combobox('getValue') || '',
                        database: data.data
                    });
                    window.parent.FR.doURLPDFPrint({
                        url: $(window.parent.document.body).data('report_url'),
                        isPopUp: false,
                        data: {
                            reportlets: reportlets
                        }
                    })
                    break;
                case 1:
                    if (!$('#contactCompanyId').combobox('getValue')) {
                        $.messager.alert('提示', '请选择客户再打印！', 'warning');
                        return;
                    }
                    reportlets.push({
                        reportlet: `${data.data}/已收款序时表打印.cpt`,
                        Sdate: $('#start').datebox('getValue'),
                        Edate: $('#end').datebox('getValue'),
                        clientName: $('#contactCompanyId').combobox('getValue') || '',
                        database: data.data
                    });
                    window.parent.FR.doURLPDFPrint({
                        url: $(window.parent.document.body).data('report_url'),
                        isPopUp: false,
                        data: {
                            reportlets: reportlets
                        }
                    })
                    break;
            }
        }
    }, 'json');
}

function btn_open_column_list() {
    let kendoGridID = '';
    switch (getCurrentIndex()) {
        case 0:
            kendoGridID = '#v_grid_3';
            break;
        case 1:
            kendoGridID = '#v_grid_4';
            break;
    }
    let options = $(kendoGridID).data('kendoGrid').getOptions().columns;
    if ($('#btn_open_column_list').length <= 0) {
        let div = $(`<div data-options="resizable:true,iconCls:'icon-text_columns',width:200,height:300,modal:true,title:'列',
                                         onClose:function(){$(this).dialog('destroy')}   " 
                          class="easyui-dialog" id="btn_open_column_list">
                   </div>`);
        let form = $('<form style="width: 100%;height: 100%;"></form>')
        for (let i of options) {
            if (i.field) {
                let checkbox = $(`<div style="width: 100%;height: auto;padding: 5px;">
                <input class="easyui-checkbox" name="${i.field}" data-options="label:'${i.title}',
                labelWidth:120,value:true,name:'${i.field}'">
                </div>`);
                form.append(checkbox);
            }
        }
        let container = $(`<div></div>`);
        form.appendTo(div);
        div.appendTo(container);
        $('body').append(container);
        $.parser.parse($('#btn_open_column_list').parent());
        let formData = {};
        options.map(item => {
            formData[item['field']] = item['hidden'] == undefined ? true : !item['hidden'];
        })
        $('#btn_open_column_list form').eq(0).form('load', formData);
        $('#btn_open_column_list form .easyui-checkbox').each(function () {
            //  绑定事件
            $(this).checkbox({
                onChange: function (checked) {
                    let opts = $(this).checkbox('options');
                    if (checked) {
                        $(kendoGridID).data('kendoGrid').showColumn(opts.name);
                    } else {
                        $(kendoGridID).data('kendoGrid').hideColumn(opts.name);
                    }
                }
            })
        })
    } else {
        $('#btn_open_column_list').dialog('open');
    }
}

function btn_export_excel() {
    // getSelectedGrid().data('kendoGrid').saveAsExcel();
    switch (getCurrentIndex()) {
        case 0:
            $('#v_grid_3').data('kendoGrid').saveAsExcel();
            break;
        case 1:
            $('#v_grid_4').data('kendoGrid').saveAsExcel();
            break;
    }
}

function stateChange(checked) {
    if (!checked && getCurrentIndex() == 0) {
        $('#contactCompanyId').combobox('clear');
        $('#contactCompanyId').combobox('disable');
        $('#start').datebox('disable');
        $('#end').datebox('disable');
    } else {
        $('#start').datebox('enable');
        $('#end').datebox('enable');
        $('#contactCompanyId').combobox('enable');
    }
    btn_search();
}

function getSelectedGrid() {
    let kendoGridID = '';
    switch (getCurrentIndex()) {
        case 0:
            kendoGridID = '#v_grid_3';
            break;
        case 1:
            kendoGridID = '#v_grid_4';
            break;
    }
    return $(kendoGridID).data('kendoGrid');
}

function btn_close() {
    window.parent.closeTab();
}

//选中事件
function initCombobox(options) {
    var columns = options.columns;
    columns.splice(0, 1);
    $('#column').combobox({
        valueField: 'field',
        textField: 'title',
        data: columns,
        editable: false
    })
}